<template>
  <p-card :bordered="false" class="containent">
    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <!-- 头部条码扫描 -->
      <p-row type="flex" :gutter="24">
        <p-col flex="auto">
          <p-form-model layout="inline" :model="topForm" :rules="rules">
            <p-row :gutter="24">
              <p-col :xl="8" :md="12">
                <p-form-model-item label="条码扫描">
                  <p-input
                    placeholder="请扫描"
                    @pressEnter="afterScan"
                  ></p-input>
                </p-form-model-item>
              </p-col>
              <p-col :xl="8" :md="12">
                <p-form-model-item label="线体">
                  <p-select
                    v-model="topForm.lineno"
                    @change="changeLine"
                    allowClear
                  >
                    <p-select-option
                      v-for="item in lines"
                      :key="item.codeValue"
                      :value="item.codeValue"
                      >{{ item.textValue }}</p-select-option
                    >
                  </p-select>
                </p-form-model-item>
              </p-col>
              <p-col :xl="8" :md="12">
                <p-form-model-item label="工站">
                  <p-tree-select
                    v-model="topForm.stationCode"
                    :tree-data="stations"
                    :dropdown-style="{ maxHeight: '500px' }"
                    tree-node-filter-prop="title"
                    show-search
                    allow-clear
                    tree-default-expand-all
                    @change="changeHandler"
                  />
                </p-form-model-item>
              </p-col>
            </p-row>
          </p-form-model>
        </p-col>
        <p-col style="padding-top: 2px">
          <p-button type="primary" @click="setConfigVisible">配置项</p-button>
          <p-button class="ml10" type="primary" @click="resetScanResults"
            >重新扫描</p-button
          >
          <p-button
            type="primary"
            @click="path('/work/datacollect/Processkey')"
            class="ml10"
            >关键件采集</p-button
          >
          <p-button
            type="primary"
            style="margin: 0 10px 0 10px"
            @click="path('/work/datacollect/Packaging')"
            >包装采集</p-button
          >
          <p-button type="primary" @click="path('/work/datacollect/Startaging')"
            >老化采集</p-button
          >
        </p-col>
      </p-row>
      <div class="product-execu-title">
        <config-step
          :current="currentStep"
          ref="configStep"
          :type="scanType"
          class="float-right"
          style="width: auto; min-width: 50%"
          size="small"
          @success="setScanOrders"
          :station-code="topForm.stationCode"
        />
        工序工单信息
      </div>
      <p-form-model
        layout="inline"
        :model="formData"
        :rules="ruleGd"
        ref="formGd"
      >
        <p-row :gutter="24">
          <p-col :md="8">
            <p-form-model-item label="工序工单">
              <p-select v-model="formData.processBillNo" @change="changHandler">
                <p-select-option
                  v-for="(item, idx) in formList"
                  :key="idx"
                  :value="item.processBillNo"
                  >{{ item.processBillNo }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="产品编码">
              <p-input
                readOnly
                placeholder=""
                v-model="formData.productcode"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="产品名称">
              <p-input
                readOnly
                placeholder=""
                v-model="formData.productname"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="生产数量">
              <p-input
                readOnly
                placeholder=""
                v-model="formData.planQty"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="接收工序">
              <p-select
                v-model="formData.acceptProcessCode"
                @change="handleChange"
              >
                <p-select-option
                  v-for="(item, idx) in receiveList"
                  :key="idx"
                  >{{ item }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="接收人员">
              <p-input
                placeholder=""
                v-model.trim="formData.acceptUserId"
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>
      <!-- 扫码信息 -->
      <div class="product-execu-title">扫码信息</div>
      <p-form-model
        layout="inline"
        :model="formitem"
        :rules="ruleScan"
        ref="ruleForm"
      >
        <p-row :gutter="24">
          <p-col :md="8">
            <p-form-model-item label="容器条码" prop="containerCode">
              <p-input
                placeholder=""
                v-model.trim="formitem.containerCode"
                read-only
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="PN/SN">
              <p-input
                placeholder=""
                v-model.trim="formitem.pnsn"
                read-only
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :md="8">
            <p-form-model-item label="操作人员" prop="operatorId">
              <p-input
                placeholder=""
                v-model.trim="formitem.operatorId"
                read-only
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>
      <!-- 底部采集表格 -->
      <p-tabs>
        <template slot="tabBarExtraContent">
          <p-button type="primary" @click="skip">半成品入库</p-button>
          <p-button
            type="primary"
            style="margin: 0 10px"
            @click="virtualBind(1)"
            >栈板绑定</p-button
          >
          <p-button type="primary" @click="bindContainer(0)">容器绑定</p-button>
        </template>
        <p-tab-pane key="order" tab="工单清单">
          <p-table
            size="middle"
            bordered
            rowKey="id"
            :pagination="false"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :rowSelection="{
              fixed: true,
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
          />
        </p-tab-pane>
        <p-tab-pane key="container" tab="容器清单">
          <p-table
            size="middle"
            bordered
            rowKey="id"
            :loading="loadingContainer"
            tableLayout="fixed"
            :columns="columns1"
            :dataSource="bindrecordData"
            :scroll="tableScroll"
            :pagination="false"
            :rowClassName="setRowClassName"
          />
        </p-tab-pane>
      </p-tabs>
    </div>
    <config
      ref="view"
      :type="scanType"
      v-model="configVisible"
      @success="onScanConfigSuccess"
      :station-code="topForm.stationCode"
    ></config>
  </p-card>
</template>

<script>
import { api } from "@/api/manage";
import { filterObj, timestampToDatetime } from "@/utils/util";
import { postAction, getAction, deleteAction } from "@/api/manage";
import mixins from "./modules/line-station";
import configMixins from "./modules/configMixins";
//工序工单采集清单
const columns = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 60,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "工序工单 ",
    align: "center",
    dataIndex: "processBillNo",
  },
  {
    title: "产品编码",
    align: "center",
    dataIndex: "productCode",
  },
  {
    title: "产品名称",
    align: "center",
    dataIndex: "productName",
  },
  {
    title: "PN/SN",
    align: "center",
    dataIndex: "pnsn",
  },
  {
    title: "组件编码",
    align: "center",
    dataIndex: "productLine",
  },
  {
    title: "需求数量",
    align: "center",
    dataIndex: "collectionQty",
  },
  {
    title: "交接数量",
    align: "center",
    dataIndex: "collectionQty",
  },
];
const Binding_record = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 60,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "线体",
    align: "center",
    dataIndex: "lineName",
  },
  {
    title: "地址码",
    align: "center",
    dataIndex: "addressCode",
  },
  {
    title: "工序工单",
    align: "center",
    dataIndex: "processBillNo",
  },
  {
    title: "产品编码",
    align: "center",
    dataIndex: "productCode",
  },
  {
    title: "产品描述",
    align: "center",
    dataIndex: "productName",
  },
  {
    title: "PN/SN",
    align: "center",
    dataIndex: "pnsn",
  },
  {
    title: "组件编码",
    align: "center",
    dataIndex: "componentCode",
  },
];
export default {
  mixins: [mixins, configMixins],
  components: {},
  data() {
    return {
      url: {
        getColumns: "/mes-manufacture/mfWip/getBarCodeCollectionHistory", //获得工序工单采集列表
        containerBind: "/mes-manufacture/mfContainer/contaierBinding", //容器绑定
        getAccept: "/mes-manufacture/mfContainer/getAcceptProcess", //接收工序
        getGZ: "/mes-craft/craft/mesPeDefinition/getAllStation", //获取工站
        containerInfo:
          "/mes-manufacture/mfContainer/getContainerInfoByContainer", //获取容器相关信息
        getGxgd: "/mes-manufacture/mfStartWork/getProcessbillNoList",
        idGetGxgd: "/mes-manufacture/mfProcess/getByNo/", //根据工序工单号获得详细工序工单
        closeContainer: "/mes-manufacture/mfContainer/closeContainer", //尾箱关闭
      },
      //工序工单信息
      formData: {
        id: null,
        processBillNo: "", //工序工单号
        planQty: null, //计划数量
        unit: "", //单位
        productcode: "", //产品编码
        productname: "", //产品名称
        starttime: null, //开始时间
        processTwoCode: "", //二级工序编码
        productType: null, //产品类型
        inspectFlag: null, //首检标志
        billnoStatus: null, //工单状态
        processVersion: "", //工艺路线版本号
        processCoding: "", //工艺路线编码
        startworkButtonFlag: null, //开工按钮显示标识
        processType: null, //工单类型
        produceBillNo: "", //生产工单
        acceptProcessCode: "", //接收工序
        acceptUserId: "", //接收人
      },
      formList: [],
      columns: [], //采集记录表格
      dataSource: [], //工序工单采集清单
      //扫描信息
      formitem: {},
      selectedRowKeys: [],
      selectionRows: [], //选中的record
      receiveList: [], //接收工序
      loading: false,
      containerInfo: {},
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: ["10", "20", "30"],
        showSizeChanger: true,
        onChange: (current) => {
          this.rightTable.pagination.current = current;
          this.getData();
        },
        onShowSizeChange: (current, pageSize) => {
          this.rightTable.pagination.pageSize = pageSize;
          this.rightTable.pagination.current = 1;
          this.getData();
        },
      },
      virtual: "",
      ruleScan: {
        containerCode: [
          { required: true, message: "请扫描容器", trigger: "blur" },
        ],
        operatorId: [
          { required: true, message: "请扫描操作人员  ", trigger: "blur" },
        ],
      },
      ruleGd: {
        processBillNo: [
          { required: true, message: "请选择工序工单", trigger: "change" },
        ],
      },
      bd: "bind",
      tags: true,
      bindrecordData: [],
      loadingContainer: false,
      scan: "",
      containerStatus: "",
      scanType: "containerBind",
    };
  },
  created() {
    this.columns = columns;
    this.columns1 = Binding_record;
    this.getGxgd(); //获得工序工单
  },
  activated() {
    this.idGetGxgd();
  },
  watch: {
    topForm: {
      deep: true,
      handler() {
        this.getGxgd();
      },
    },
  },
  methods: {
    setRowClassName(record) {
      if (record.containerCheckStatus) {
        return "clickRowStyl";
      } else {
        return "clickRowSty2";
      }
    },
    afterScan(event) {
      this.addScanResults(event);
      const len = this.scanResults.length;
      const code = this.scanResults[len - 1];
      const item = this.scanOrders[len - 1];
      switch (item.scanType) {
        // 产品码
        case 1:
          this.formitem.pnsn = code;
          this.bindContainerSingle();
          break;
        // 关键件条码
        // case 2:
        //   break
        // 容器码
        case 3:
          this.formitem.containerCode = code;
          this.getContainerInfo();
          break;
        // 人员条码
        case 4:
          this.formitem.operatorId = code;
          break;
        // 物料条码
        // case 5:
        //   break
        // 地址码
        // case 6:
        //   this.form.addressCode = code;
        //   break;
      }
    },
    customResetScanResults() {
      this.formitem = {};
      this.bindrecordData = [];
    },
    //获得容器信息
    getContainerInfo(refresh) {
      this.loadingContainer = true;
      let params = {
        containerCode: formitem.containerCode,
      };
      postAction(this.url.containerInfo, params)
        .then((res) => {
          if (res.success) {
            this.setRowClassName(res.data.containerCheckStatus);
            this.containerInfo = res.data;
            this.bindrecordData = res.data.childrens;
            this.bindrecordData.map((item) => {
              this.$set(item, "addressCode", res.data.addressCode);
              this.$set(
                item,
                "containerCheckStatus",
                res.data.containerCheckStatus
              );
            });
            if (!refresh) {
              this.$message.success("扫码成功");
            }
          } else {
            this.$message.warning(res.msg);
            this.bindrecordData = [];
          }
        })
        .finally(() => {
          this.loadingContainer = false;
        });
    },
    //获得工序工单列表
    getGxgd() {
      getAction(this.url.getGxgd, this.topForm).then((res) => {
        if (res.success) {
          this.formList = res.data;
        }
      });
    },
    //获取工序工单未采集清单
    getColumns() {
      if (this.formData.processBillNo) {
        this.loading = true;
        let params = {
          limit: this.pagination.pageSize,
          pageNo: this.pagination.current,
          binFlag: 0,
          processbillId: this.formData.id,
          processbillNo: this.formData.processBillNo,
          stationCode: this.topForm.station,
        };
        postAction(this.url.getColumns, params).then((res) => {
          if (res.success) {
            this.dataSource = res.data;
            this.getAccept(); //获得接收工序
          }
          this.loading = false;
        });
      }
    },
    //获得接收工序
    getAccept() {
      let params = {
        processbillId: this.formData.id,
        processbillNo: this.formData.processBillNo,
        stationCode: this.topForm.station,
      };
      postAction(this.url.getAccept, params).then((res) => {
        this.receiveList = res.data;
      });
    },
    //容器绑定勾选
    bindContainer(type) {
      this.$refs.ruleForm.validate((value) => {
        if (value) {
          if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
            this.$message.warning("请先选中一条记录");
            return false;
          }
          this.loading = true;
          this.loadingContainer = true;
          let produceCode = this.containerInfo.productCode;
          // if (!produceCode || item.productCode == produceCode) {
          let childs = this.selectionRows.map((item) => {
            let { wipId, pnsn } = item;
            return { wipId, barCodeType: 1, pnsn };
          });
          let { acceptProcessCode, acceptUserId } = this.formData;
          let params = {
            acceptProcessCode,
            acceptProcessName: "",
            acceptUserId,
            acceptUserName: "",
            childs,
            containerCode: this.formitem.containerCode,
            linename: this.topForm.lineName,
            lineno: this.topForm.lineno,
            stationCode: this.topForm.stationCode,
            stationName: this.topForm.stationName,
            plankFlag: type,
            scanBindFlag: 0,
          };
          postAction(this.url.containerBind, params)
            .then((res) => {
              if (res.data) {
                this.$message.success("绑定成功");
                this.getColumns();
                this.getContainerInfo("refresh");
                this.selectedRowKeys = [];
              } else {
                this.$message.warning(res.msg);
              }
            })
            .finally(() => {
              this.loading = false;
              this.loadingContainer = false;
            });
        }
      });
    },
    //扫描绑定
    bindContainerSingle() {
      if (!this.formitem.containerCode) {
        this.$message.error("未识别到容器");
      }
      let produceCode = this.containerInfo.productCode;
      let childs = [{ pnsn: this.formitem.pnsn, barCodeType: 1 }];
      let { acceptProcessCode, acceptUserId } = this.formData;
      let params = {
        acceptProcessCode,
        acceptProcessName: "",
        acceptUserId,
        acceptUserName: "",
        childs,
        containerCode: this.formitem.containerCode,
        linename: this.topForm.lineName,
        lineno: this.topForm.lineno,
        stationCode: this.topForm.stationCode,
        stationName: this.topForm.stationName,
        plankFlag: 0,
        scanBindFlag: 1,
      };
      this.loadingContainer = true;
      postAction(this.url.containerBind, params)
        .then((res) => {
          if (res.success) {
            this.$message.success("绑定成功");
            // this.msg = "绑定成功";
            this.getContainerInfo("refresh");
          } else {
            this.$message.warning(res.msg);
            // this.msg = res.msg;
            // this.msgType = "warning";
          }
        })
        .finally(() => {
          this.loadingContainer = false;
        });
    },
    // 栈板绑定
    virtualBind(type) {
      if (!this.virtual) return this.$message.warning("暂时缺少栈板码");
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      let childs = this.selectionRows.map((item) => {
        let { wipId, pnsn } = item;
        return { wipId, barCodeType: 1, pnsn };
      });
      let { acceptProcessCode, acceptUserId } = this.formData;
      let params = {
        acceptProcessCode,
        acceptProcessName: "",
        acceptUserId,
        acceptUserName: "",
        childs,
        containerCode: virtual,
        linename: this.topForm.lineName,
        lineno: this.topForm.lineno,
        stationCode: this.topForm.stationCode,
        stationName: this.topForm.stationName,
        plankFlag: type,
      };
      postAction(this.url.containerBind, params).then((res) => {
        if (res.success) {
          this.$message.success("绑定成功");
          // this.msg = "绑定成功";
          this.getColumns();
          this.selectedRowKeys = [];
        }
      });
    },
    skip() {
      this.$router.push("/work/datacollect/Semifinished");
    },
    changHandler(val) {
      let item = this.formList.filter((items) => items.processBillNo == val);
      const { productcode, productname, planQty, id } = item[0];
      this.formData.productcode = productcode;
      this.formData.productname = productname;
      this.formData.planQty = planQty;
      this.formData.id = id;
      this.getColumns();
    },
    handleChange() {},
    // 根据id获取工序工单
    idGetGxgd() {
      this.topForm.lineno = this.$route.query.lineno;
      this.topForm.stationCode = this.$route.query.stationCode;
      if (this.$route.query.data) {
        getAction(this.url.idGetGxgd + this.$route.query.data).then((res) => {
          if (res.success) {
            this.formData = res.data;
            this.formData.processBillNo = res.data.processbillno;
            this.getColumns();
          }
        });
      }
    },
    //多选框
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      console.log(this.selectedRowKeys, this.selectionRows);
    },
  },
};
</script>
<style lang='less' scoped>
.containent {
  .wrap1 {
    /deep/ .clickRowStyl td {
      color: #4064e9 !important;
    }
    /deep/ .clickRowSty2 td {
      // color: red !important;
    }
    .poros-alert {
      text-align: center;
    }
  }
}
</style>